<template>
  <div class="login-container">
    <div class="login-box" :class="{ 'is-register': fromType }">
      <!-- 左侧登录表单 -->
      <div class="login-form" v-if="!loginType">
        <!-- 返回按钮 -->
        <div class="page-header" v-if="fromType">
          <div class="back-btn hover-scale" @click="handchange">
            <el-icon><ArrowLeft /></el-icon>
            <span>返回登录</span>
          </div>
          <div class="header-title">用户注册</div>
        </div>
        <div class="system-title" :class="{ 'fade-in': mounted }" v-else>
          <el-icon class="title-icon"><Platform /></el-icon>
          学生画像综合管理系统
        </div>
        <div class="login-type">
          <div class="type-title slide-in">
            <span class="title-text">{{ fromType ? '用户注册' : '用户登录' }}</span>
            <div class="title-decoration"></div>
          </div>
          <!-- 第三方登录按钮 -->
          <div class="third-party-login slide-in">
            <el-button class="wechat-btn hover-scale" @click="handleWechatLogin">
              <el-icon><ChatRound /></el-icon>
              微信一键登录
            </el-button>
            <el-button class="phone-btn hover-scale" @click="handlePhoneLogin">
              <el-icon><Iphone /></el-icon>
              手机号快捷登录
            </el-button>
          </div>
          <div class="divider slide-in">
            <span class="line"></span>
            <span class="text">其他登录方式</span>
            <span class="line"></span>
          </div>
          <!-- 登录表单 -->
          <el-scrollbar class="form-scrollbar" :class="{ 'show-scrollbar': fromType }">
            <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="form slide-in" size="large">
              <el-form-item prop="userName">
                <el-input 
                  v-model="loginForm.userName" 
                  :placeholder="fromType ? '请输入姓名' : '请输入用户名'" 
                  :prefix-icon="UserFilled"
                />
              </el-form-item>
              <el-form-item prop="studentId" v-if="fromType">
                <el-input 
                  v-model="loginForm.studentId" 
                  placeholder="请输入学号/工号" 
                  :prefix-icon="Document"
                />
              </el-form-item>
              <el-form-item prop="passWord">
                <el-input 
                  v-model="loginForm.passWord" 
                  type="password" 
                  placeholder="请输入密码" 
                  :prefix-icon="Lock" 
                  show-password
                />
              </el-form-item>
              <el-form-item prop="code" v-if="fromType">
                <el-input
                  v-model="loginForm.code"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  maxlength="4"
                >
                  <template #append>
                    <img
                      src="./验证码.png"
                      alt="验证码"
                      class="verify-code"
                      @click="refreshCode"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button 
                  type="primary" 
                  class="submit-btn hover-scale" 
                  :loading="loading"
                  @click="handleDirectLogin"
                >
                  {{ fromType ? '注册' : '登录' }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-scrollbar>
          <!-- 切换登录/注册 -->
          <div class="switch-type slide-in">
            {{ fromType ? '已有账号？' : '还没有账号？' }}
            <el-link type="primary" class="hover-scale" @click="handchange">
              {{ fromType ? '返回登录' : '立即注册' }}
            </el-link>
          </div>
        </div>
      </div>
      
      <!-- 微信登录组件 -->
      <WechatLogin
        v-if="loginType === 'wechat'"
        @back="loginType = ''"
        @login-success="handleLoginSuccess"
      />
      
      <!-- 手机号登录组件 -->
      <PhoneLogin
        v-if="loginType === 'phone'"
        @back="loginType = ''"
        @login-success="handleLoginSuccess"
      />
      
      <!-- 右侧展示区 -->
      <div class="login-banner">
        <img src="./图书馆正面.png" alt="华北理工大学图书馆" class="banner-img">
        <div class="banner-overlay"></div>
        <div class="school-info fade-in">
          <img src="../../assets/logo.png" alt="华北理工大学" class="school-logo">
        </div>
        <div class="banner-content">
          <h2 class="banner-title slide-in-right">智慧校园 · 数字画像</h2>
          <p class="banner-desc slide-in-right">让数据驱动教育创新</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { UserFilled, Lock, Document, Key, ChatRound, Iphone, School, Platform, ArrowLeft } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { getCode, userAuthentication, login } from '../../api/api';
import { useRouter } from 'vue-router';
import WechatLogin from '../../components/login/WechatLogin.vue';
import PhoneLogin from '../../components/login/PhoneLogin.vue';

const router = useRouter();
const loginFormRef = ref();
const fromType = ref(false);
const captchaImage = ref('');
const loading = ref(false);
const mounted = ref(false);
const loginType = ref('');

// 登录表单数据
const loginForm = reactive({
  userName: '',
  studentId: '',
  passWord: '',
  code: ''
});

// 表单验证规则
const rules = reactive({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能小于2个字符', trigger: 'blur' }
  ],
  studentId: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
    { pattern: /^\d{8,12}$/, message: '请输入正确的学号/工号格式', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度应为4位', trigger: 'blur' }
  ]
});

// 切换登录/注册
const handchange = () => {
  fromType.value = !fromType.value;
  loginFormRef.value?.resetFields();
  // 重置表单验证状态
  if (loginFormRef.value) {
    loginFormRef.value.clearValidate();
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  // 这里添加获取验证码图片的逻辑
};

// 处理微信登录
const handleWechatLogin = () => {
  loginType.value = 'wechat';
};

// 处理手机号登录
const handlePhoneLogin = () => {
  loginType.value = 'phone';
};

// 处理登录成功
const handleLoginSuccess = (data) => {
  localStorage.setItem('pz_token', data.token);
  localStorage.setItem('pz_userInfo', JSON.stringify(data.userInfo));
  localStorage.setItem('student_class', JSON.stringify(data.student_class));
  router.push('/profiles');
};

// 直接登录处理
const handleDirectLogin = () => {
  if (fromType.value) {
    // 如果是注册状态，保持原有逻辑
    submitForm();
  } else {
    // 如果是登录状态，直接跳转
    // router.push('/profiles');
    submitForm();
  }
};

// 表单提交
const submitForm = async () => {
  if (!loginFormRef.value) return;
  
  try {
    loading.value = true;
    const valid = await loginFormRef.value.validate();
    
    if (valid) {
      if (fromType.value) {
        // 注册逻辑
        const { data } = await userAuthentication(loginForm);
        if (data.code === 10000) {
          ElMessage.success('注册成功，请登录');
          fromType.value = false;
          loginFormRef.value?.resetFields();
        }
      } else {
        // 登录逻辑
        const { data } = await login(loginForm);
        if (data.code === 10000) {
          ElMessage.success('登录成功！');
          localStorage.setItem('pz_token', data.data.token);
          localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo));
          localStorage.setItem('student_class', JSON.stringify(data.data.student_class));
          router.push('/profiles');
        }
      }
    }
  } catch (error) {
    console.error('表单提交错误:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  refreshCaptcha();
  mounted.value = true;
});
</script>

<style lang="less" scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  overflow: hidden;
  
  .login-box {
    width: 1200px;
    height: 600px;
    display: flex;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    transition: height 0.3s ease;
    
    &.is-register {
      height: 700px;
    }
    
    .login-form {
      width: 500px;
      padding: 48px;
      background-color: #fff;
      position: relative;
      z-index: 1;
      
      .page-header {
        display: flex;
        align-items: center;
        margin-bottom: 40px;
        
        .back-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #409EFF;
          cursor: pointer;
          font-size: 16px;
          transition: all 0.3s ease;
          
          .el-icon {
            font-size: 18px;
          }
          
          &:hover {
            transform: translateX(-5px);
            opacity: 0.8;
          }
        }
        
        .header-title {
          margin-left: auto;
          font-size: 24px;
          font-weight: 600;
          color: #1a1a1a;
        }
      }
      
      .form-scrollbar {
        max-height: 400px;
        overflow-y: auto;
        
        &.show-scrollbar {
          padding-right: 8px;
          
          &::-webkit-scrollbar {
            width: 6px;
          }
          
          &::-webkit-scrollbar-thumb {
            background-color: #e4e7ed;
            border-radius: 3px;
          }
          
          &::-webkit-scrollbar-track {
            background-color: #f5f7fa;
          }
        }
      }
      
      .system-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 24px;
        font-weight: bold;
        color: #1a1a1a;
        margin-bottom: 48px;
        
        .title-icon {
          font-size: 32px;
          color: #409EFF;
        }
      }
      
      .login-type {
        .type-title {
          position: relative;
          display: inline-block;
          margin-bottom: 32px;
          
          .title-text {
            font-size: 28px;
            font-weight: 600;
            background: linear-gradient(45deg, #409eff, #007fff);
            -webkit-background-clip: text;
            color: transparent;
            letter-spacing: 1px;
          }
          
          .title-decoration {
            position: absolute;
            bottom: -4px;
            left: 0;
            width: 40%;
            height: 4px;
            background: linear-gradient(90deg, #409eff, transparent);
            border-radius: 2px;
          }
        }
        
        .third-party-login {
          display: flex;
          gap: 16px;
          margin-bottom: 32px;
          
          .wechat-btn, .phone-btn {
            flex: 1;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            transition: all 0.3s ease;
            
            .el-icon {
              font-size: 20px;
            }
          }
          
          .wechat-btn {
            color: #07c160;
            &:hover {
              background-color: #f0f9eb;
              border-color: #07c160;
            }
          }
          
          .phone-btn {
            color: #409eff;
            &:hover {
              background-color: #ecf5ff;
              border-color: #409eff;
            }
          }
        }
        
        .divider {
          display: flex;
          align-items: center;
          margin: 24px 0;
          
          .line {
            flex: 1;
            height: 1px;
            background-color: #e4e7ed;
          }
          
          .text {
            padding: 0 16px;
            color: #909399;
            font-size: 14px;
          }
        }
        
        .form {
          margin-top: 24px;
          
          :deep(.el-input__wrapper) {
            background-color: #f5f7fa;
            border-radius: 8px;
            box-shadow: none !important;
            border: 1px solid #e4e7ed;
            padding: 0 15px;
            
            &:hover {
              border-color: #409eff;
            }
            
            &.is-focus {
              border-color: #409eff;
              border-width: 1px;
              box-shadow: 0 0 0 1px #409eff !important;
            }
          }
          
          :deep(.el-input__inner) {
            height: 44px;
          }
          
          .verify-code {
            display: flex;
            gap: 12px;
            
            .el-input {
              flex: 1;
            }
            
            .captcha-img {
              width: 120px;
              height: 44px;
              border-radius: 8px;
              cursor: pointer;
              object-fit: cover;
            }
          }
          
          .submit-btn {
            width: 100%;
            height: 44px;
            font-size: 16px;
            border-radius: 8px;
            margin-top: 8px;
          }
        }
        
        .switch-type {
          margin-top: 24px;
          text-align: center;
          color: #606266;
          font-size: 14px;
          
          .el-link {
            margin-left: 8px;
            font-weight: 500;
          }
        }
      }
    }
    
    .login-banner {
      flex: 1;
      position: relative;
      overflow: hidden;
      
      .banner-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transform: scale(1);
        transition: transform 0.3s ease;
        filter: brightness(1.1) contrast(1.1);
        
        &:hover {
          transform: scale(1.05);
        }
      }
      
      .banner-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, 
          rgba(64, 158, 255, 0.5), 
          rgba(0, 127, 255, 0.5)
        );
        z-index: 1;
      }
      
      .school-info {
        position: absolute;
        top: 40px;
        right: 40px;
        z-index: 2;
        
        .school-logo {
          width: 120px;
          height: 40px;
          object-fit: contain;
        }
      }
      
      .banner-content {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        z-index: 2;
        width: 100%;
        padding: 0 48px;
        
        .banner-title {
          font-size: 36px;
          font-weight: bold;
          color: #fff;
          margin-bottom: 16px;
          letter-spacing: 2px;
        }
        
        .banner-desc {
          font-size: 18px;
          color: rgba(255, 255, 255, 0.9);
          letter-spacing: 1px;
        }
      }
    }
  }
}

// 动画效果
.fade-in {
  animation: fadeIn 0.8s ease-out forwards;
}

.slide-in {
  animation: slideIn 0.6s ease-out forwards;
}

.slide-in-right {
  animation: slideInRight 0.8s ease-out forwards;
}

.hover-scale {
  transition: transform 0.2s ease;
  
  &:hover {
    transform: scale(1.02);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

// 响应式调整
@media screen and (max-width: 1200px) {
  .login-box {
    width: 90%;
    margin: 0 20px;
  }
}

@media screen and (max-height: 700px) {
  .login-box {
    height: 90vh;
    
    &.is-register {
      height: 95vh;
    }
  }
}

.verify-code {
  height: 32px;
  cursor: pointer;
  vertical-align: middle;
  margin: -6px -12px;
}
</style>
